<template>
  <view class="wrapper">
    <view class="search">
      <u-search
          placeholder="请输入关键字"
          v-model="keyword"
          height="60rpx"
          searchIconSize="50rpx"
          @search="onSearch"
          @custom="onSearch"
      ></u-search>
    </view>
    <swiper class="swiper" circular :indicator-dots="false" :autoplay="true" :interval="3000" :duration="500">
      <swiper-item
          v-for="(item, index) in home.swiper"
          :key="index"
          class="swpier-item"
      >
        <view class="image" @click="clickSwiper(item)">
          <u--image width="100%" height="100%" :fade="true" duration="450" lazy-load mode="widthFix" :src="baseUrl + item.image.path" v-if="item.image"></u--image>
        </view>
      </swiper-item>
    </swiper>
    <view class="news" v-if="home.news">
      <u-notice-bar
          :text="home.news.title"
          mode="link"
          fontSize="24rpx"
          color="#666"
          bgColor="#fff"
          @click="goNews"></u-notice-bar>
    </view>
    <view class="nav" v-if="home.nav && home.nav.data">
      <view
          v-for="(item, index) in home.nav.data"
          :key="index"
          class="nav-item"
          :class="{'more': home.nav.total == 5}"
          @click="clickNav(item)">
        <view class="image" v-if="item.image && item.image.path" >
          <u--image lazy-load width="100%" height="100%" :fade="true" duration="450" mode="widthFix" :src="baseUrl + item.image.path" v-if="item.image"></u--image>
        </view>
        <span class="name">{{ item.name }}</span>
      </view>
    </view>
    <view class="product" v-if="false">
      <view v-for="(item, index) in home.recommend" :key="index" class="product-item" @click="clickProduct(item)">
        <view class="image">
          <u--image lazy-load width="100%" height="100%" :fade="true" duration="450" mode="widthFix" :src="baseUrl + item.mainImage.path" v-if="item.mainImage"></u--image>
        </view>
        <view class="desc">
          <view class="title">{{ item.title }}</view>
          <view class="price_old">{{ item.title_sub }}</view>
          <view class="price">￥{{ item.price }}</view>
          <view class="button">立即购买</view>
        </view>
      </view>
    </view>
    <!-- 拼团区 -->
    <!--<u-sticky :offset-top="top">-->
    <view class="category" v-if="false">
      <view class="text">
        <view>热门拼团</view>
      </view>
      <u-tabs
          v-if="false"
          class="tabs"
          :list="groupCategoryList"
          :current="groupCurrent"
          @change="handleCategoryGroup"
          :activeStyle="{
              color: activeColor,
              transform: 'scale(1.05)',
              fontSize: '24rpx'
            }"
          :inactiveStyle="{
              transform: 'scale(1)',
              fontSize: '24rpx'
            }"
          :lineColor="activeColor"
          lineHeight="5"
      ></u-tabs>
    </view>
    <!--</u-sticky>-->
    <view class="product" v-if="false">
      <!--<v-list :list="groupProductList" :show-nothing="false" />-->
      <!--<view @click="moreProduct" class="more" v-if="current > 0 && productList.length > 0">点击查看更多</view>-->
      <v-item :list="groupProductList" />
      <view class="nothing" v-if="groupProductList.length === 0">暂无相关信息</view>
    </view>
    <!-- 推荐商品 -->
    <!--<u-sticky :offset-top="top">-->
    <view class="category">
      <view class="text">
        <view>推荐商品</view>
      </view>
      <u-tabs
          v-if="false"
          class="tabs"
          :list="categoryList"
          :current="current"
          @change="handleCategory"
          :activeStyle="{
              color: activeColor,
              transform: 'scale(1.05)',
              fontSize: '24rpx'
            }"
          :inactiveStyle="{
              transform: 'scale(1)',
              fontSize: '24rpx'
            }"
          :lineColor="activeColor"
          lineHeight="5"
      ></u-tabs>
    </view>
    <!--</u-sticky>-->
    <view class="product">
      <v-list :list="productList" :show-nothing="false" />
      <view @click="moreProduct" class="more" v-if="current > 0 && productList.length > 0">点击查看更多</view>
      <view class="nothing" v-if="false && groupProductList.length === 0">暂无相关信息</view>
    </view>
    <v-tab :selected="'/pages/index/index'" />
    <template v-if="red > 0">
      <view class="mask" @click="noRedPacket"></view>
      <view class="red_packet" :class="{'no' : !red}" @click="redPacket">
        <u--image
            lazy-load
            class="img"
            width="600rpx"
            height="1066rpx"
            :fade="true" duration="450" mode="scaleToFill"
            :src="baseUrl + red_packet"></u--image>
      </view>
    </template>
    <!-- 最新商品 -->
    <!--<u-sticky :offset-top="top">-->
    <view class="category">
      <view class="text">
        <view>最新商品</view>
      </view>
      <u-tabs
          v-if="false"
          class="tabs"
          :list="categoryList"
          :current="current"
          @change="handleCategory"
          :activeStyle="{
              color: activeColor,
              transform: 'scale(1.05)',
              fontSize: '24rpx'
            }"
          :inactiveStyle="{
              transform: 'scale(1)',
              fontSize: '24rpx'
            }"
          :lineColor="activeColor"
          lineHeight="5"
      ></u-tabs>
    </view>
    <!--</u-sticky>-->
    <view class="product">
      <v-list :list="groupProductList" :show-nothing="false" />
      <view @click="moreProduct" class="more" v-if="current > 0 && productList.length > 0">点击查看更多</view>
      <view class="nothing" v-if="false && groupProductList.length === 0">暂无相关信息</view>
    </view>
    <v-tab :selected="'/pages/index/index'" />
    <template v-if="red > 0">
      <view class="mask" @click="noRedPacket"></view>
      <view class="red_packet" :class="{'no' : !red}" @click="redPacket">
        <u--image
            lazy-load
            class="img"
            width="600rpx"
            height="1066rpx"
            :fade="true" duration="450" mode="scaleToFill"
            :src="baseUrl + red_packet"></u--image>
      </view>
    </template>
    <u-modal :show="showRed" :title="`金额: ￥${red}, 已保存到您的余额`" @confirm="closeRed"></u-modal>
    <!-- app tip -->
    <u-modal
        :show="app_tip"
        :title="'用户提示'"
        :confirmText="'同意'"
        :cancelText="'退出'"
        showConfirmButton
        showCancelButton
        @confirm="goApp"
        @cancel="closeApp"
    >
      <view class="slot-content">
        <rich-text :nodes="app_tip_content"></rich-text>
        <view class="app-link">
          <text>请您阅读</text>
          <text class="color" @click="goAgreementUser">《用户协议》</text>
          <text>和</text>
          <text class="color" @click="goAgreementPrivacy">《隐私政策》</text>
        </view>
      </view>
    </u-modal>
    <view class="space"></view>
  </view>
</template>

<script>
import Tab from '../../components/tab'
import color from '@/config/color.js'
import config from '../../config/config'
import base64 from '../../util/base64'
import Home from '../../api/home'
import List from '../../components/list'
import Item from '../group/components/Item'
import Balance from '../../api/balance'
import Fav from '../../api/fav'
import User from '../../api/user'
const homeModel = new Home()
const balanceModel = new Balance()
const favModel = new Fav()
const userModel = new User()

// 同意协议
const key = 'app-key-0228'

export default {
  components: {
    'v-list': List,
    'v-tab': Tab,
    'v-item': Item
  },
  data() {
    return {
      activeColor: color.main_color,
      top: 0,
      home: {},
      baseUrl: config.baseUrl,
      productList: [],
      groupProductList: [],
      categoryList: [],
      groupCategoryList: [],
      keyword: '',
      // 推荐商品
      recommendProduct: [],
      allProduct: [],
      groupProduct: [],
      current: 0,
      groupCurrent: 0,
      // 红包
      red_packet: '/red_packet.png',
      red: 0,
      red_id: 0,
      showRed: false,
      app_tip: false,
      app_tip_content: ''
    }
  },
  // 分享
  onShareAppMessage(res) {
    return {
      // title: '快递熊小二',
      path: '/pages/index/index?scene=' +
          (this.$store.getters['User/info'] ? this.$store.getters['User/info'].id : 0),
      // 这里还可以定义图片
      // imageUrl: '',
    }
  },
  onShow() {
    /* #ifdef H5 */
    this.top = 45
    /* #endif */

    // app 需要提示
    /*#ifdef APP-PLUS || H5*/
    // App端特有的逻辑
    // 用uni配置的
    // const tip = uni.getStorageSync(key)
    // if (!tip) {
    //   this.app_tip = true
    //   userModel.getAgreementAll().then(response => {
    //     let { data } = response
    //     data = base64.parse(data)
    //     this.app_tip_content = data.agreement_x
    //   })
    // }
    /*#endif*/

    // 加载拼团数据
    // homeModel.getGroup().then(response => {
    //   let { data } = response
    //   data = base64.parse(data)
    //   this.groupProductList = [...data.list]
    // })

    // 加载红包
    // this._isLogin().then(() => {
    //   balanceModel.getTicket().then(response => {
    //     let { data } = response
    //     data = base64.parse(data)
    //     if (data.red) {
    //       this.red = +data.red.ticket
    //       this.red_id = data.red.id
    //     }
    //   })
    // }).catch(() => {
    //
    // })
  },
  onLoad(options) {
    // 分享
    /*#ifdef MP-WEIXIN*/
    // 微信小程序端执行的逻辑
    // uni.showShareMenu({
    //   menus: ['shareAppMessage', 'shareTimeline'],
    //   success: res => {
    //
    //   }
    // })
    /*#endif*/
    // console.log(process.env.NODE_ENV)

    // 小程序推荐人
    if (options.scene && (options.scene > 0 || options.scene.length > 0)) {
      console.log('referrer', options.scene)
      // todo 商品分享
      homeModel.setReferrer(options.scene)
    }

    uni.hideTabBar({
      animation: false,
      success: () => {

      },
      fail: () => {

      }
    })
    uni.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: this.activeColor,
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
    this.fetchData()
  },
  onPullDownRefresh() {
    this.current = 0
    this.keyword = ''
    this.fetchData()
  },
  methods: {
    // 同意APP
    goApp() {
      this.app_tip = false
      uni.setStorageSync(key, true)
    },
    // 退出APP
    closeApp() {
      // uni.navigateBack({
      //   delta: 1
      // })
      this.app_tip = false
      /*#ifdef APP-PLUS*/
      if (plus) {
        plus.runtime.quit()
      }
      /*#endif*/
    },
    goAgreementPrivacy() {
      uni.navigateTo({
        url: '/sub_common/user/agreement_privacy'
      })
    },
    goAgreementUser() {
      uni.navigateTo({
        url: '/sub_common/user/agreement_user'
      })
    },

    _isLogin() {
      return new Promise((resolve, reject) => {
        const token = this.$store.getters['User/token']
        if (!token) {
          reject()
        } else {
          favModel.isLogin({ token }).then(response => {
            let { data } = response
            data = base64.parse(data)
            if (data.isLogin) {
              resolve()
            } else {
              // 没有登录
              reject()
            }
          })
        }
      })
    },

    noRedPacket() {
      // console.log(111)
      this.red = 0
    },
    redPacket() {
      // console.log(22)
      // this.red = 0
      // console.log(this.red_id)
      balanceModel.saveTicket({ id: this.red_id }).then(() => {
        // uni.showToast({
        //   icon: 'none',
        //   title: `金额: ￥${this.red}, 已保存到您的余额`
        // })
        // console.log(this.red)
        this.showRed = true
        // this.red = 0
      })
    },
    closeRed() {
      this.red = 0
      this.showRed = false
    },
    fetchData() {
      homeModel.getHome().then(response => {
        let { data } = response
        data = base64.parse(data)
        this.home = data

        // console.log(this.home)

        uni.setNavigationBarTitle({
          title: this.home.app_name
        })

        // 购物区
        this.recommendProduct = this.home.recommend
        this.categoryList = [{ name: '推荐商品' }, ...this.home.category]
        this.productList = [...this.recommendProduct]
        // console.log('hh-', data)

        // 拼团区
        // this.groupProduct = this.home.recommend_group
        this.groupProduct = this.home.product_list
        this.groupProductList = [...this.groupProduct]
        this.groupCategoryList = [{ name: '最新' }, ...this.home.category_group]

        uni.stopPullDownRefresh();
      })
    },
    goNews() {
      uni.navigateTo({
        url: `/sub_service/news/detail?id=${this.home.news.id}`
      })
    },
    clickSwiper(item) {
      if (item.url) {
        uni.navigateTo({
          url: item.url
        })
      }
    },
    clickNav(item) {
      if (item.url) {
        uni.navigateTo({
          url: item.url
        })
      }
    },
    clickProduct(item) {
      uni.navigateTo({
        url: `/sub_product/detail/index?id=${item.id}`
      })
    },
    handleCategoryGroup(tab) {
      this.groupCurrent = tab.index
      // console.log(tab)
      if (!tab.id) {
        this.groupProductList = [...this.groupProduct]
      } else {
        const id = this.groupCategoryList[this.groupCurrent].id
        homeModel.getCateProductGroup({ id }).then(response => {
          let { data } = response
          data = base64.parse(data)
          this.groupProductList = [...data.list]
        })
      }
    },
    // 分类商品
    handleCategory(tab) {
      this.current = tab.index
      // console.log(tab)
      if (!tab.id) {
        this.productList = [...this.recommendProduct]
      } else {
        const id = this.categoryList[this.current].id
        homeModel.getCateProduct({ id }).then(response => {
          let { data } = response
          data = base64.parse(data)
          this.productList = [...data.list]
        })
      }
    },
    // 更多分类产品
    moreProduct() {
      const id = this.categoryList[this.current].id
      uni.navigateTo({
        url: `/sub_product/category/index?id=${id}`
      })
    },
    onSearch() {
      if (this.keyword) {
        uni.navigateTo({
          url: `/sub_common/search/index?keyword=${this.keyword}`
        })
      } else {
        uni.showToast({
          icon: 'none',
          title: '请输入关键字'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
//$swiper_height: 335rpx;
$swiper_height: 942rpx;

// 底部空白
.space {
  height: 100rpx;
}

// APP 提示
.app-link {
  display: flex;
  margin-top: 10px;
  justify-content: start;
  .color {
    margin: 0 10rpx;
    color: $main_color;
  }
}

// 红包
.mask {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  height: 1000vh;
  background: black;
  opacity: 0.5;
}
.red_packet {
  position: absolute;
  left: 75rpx;
  top: 50rpx;
  width: 600rpx;
  height: 1066rpx;
  transition: all 0.3s linear;
  background: red;
  z-index: 100;
  .img {
    width: 100%;
    height: 100%;
  }
  &.no {
    left: 0rpx;
    top: 0rpx;
    width: 1500rpx;
    height: 3334rpx;
    opacity: 0;
    .img {
    }
  }
}
.wrapper {
  padding: 20rpx 20rpx 100rpx 20rpx;
  background: $background_color;
  .swiper {
    height: $swiper_height;
    .image {
      //background: red;
      height: $swiper_height;
      border-radius: 10rpx;
      overflow: hidden;
      image {
        width: 100%;
        height: 100%;
        display: block;
        margin: auto;
      }
    }
  }
  .nav {
    margin: 20rpx 0;
    background: white;
    display: flex;
    flex-wrap: wrap;
    border-radius: 10rpx;
    justify-content: space-around;
    //justify-content: start;
    .nav-item {
      width: 25%;
      //width: 20%;
      box-sizing: border-box;
      padding: 0 2.5%;
      &.more {
        width: 20%;
      }
      margin-bottom: 10rpx;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      .image {
        padding: 30rpx;
        overflow: hidden;
        //background: red;
        image {
          width: 100%;
          height: 100%;
          display: block;
          margin: auto;
        }
      }
      .name {
        //font-size: 24rpx;
        color: #000;
        //font-weight: 700;
        height: 60rpx;
        line-height: 60rpx;
        margin-top: -20rpx;
        text-align: center;
      }
    }
  }
  .news {
    margin: 20rpx 0;
    border-radius: 10rpx;
    overflow: hidden;
  }
  .search {
    background: white;
    margin: 0rpx 0;
    border-radius: 10rpx;
    overflow: hidden;
    box-sizing: border-box;
    padding: 10px;
    margin-bottom: 10px;
  }
  .category {
    background: white;
    margin: 20rpx 0;
    border-radius: 10rpx;
    overflow: hidden;
    box-sizing: border-box;
    padding: 0 10px;
    display: flex;
    align-items: center;
    .text {
      height: 28px;
      line-height: 28px;
      width: 200rpx;
      //font-size: 24rpx;
      font-weight: 700;
      color: $main_color;
      //transform: rotate(-30deg);
      //border-right: 1rpx solid $main_color;
      view {
        //transform: rotate(-3deg);
      }
    }
    .tabs {
      flex: 1;
    }
  }
  .product {
    .nothing {
      //background: white;
      padding: 20rpx;
      color: #999999;
      //font-size: 24rpx;
    }
    //padding-bottom: 20px;
    .product-list {
      //min-height: 800px;
    }
    .more {
      padding: 20rpx;
      border-radius: 10rpx;
      background: white;
      //font-size: 24rpx;
      color: #666;
      text-align: center;
    }
    .product-item {
      display: flex;
      border-radius: 10rpx;
      padding: 20rpx;
      margin-bottom: 20rpx;
      background: white;
      .image {
        width: 240rpx;
        height: 240rpx;
        padding: 10rpx;
        overflow: hidden;
        image {
          width: 100%;
          height: 100%;
          display: block;
          margin: auto;
        }
      }
      .desc {
        flex: 1;
        text-align: left;
        position: relative;
        margin-top: 20rpx;
        padding-left: 20rpx;
        //font-size: 24rpx;
        .title {
          font-weight: 700;
          font-size: 24rpx;
          line-height: 40rpx;
        }
        .price_old, .price {
          line-height: 36rpx;
          color: #808080;
        }
        .price {
          color: red;
          //font-size: 30rpx;
          font-weight: 700;
          height: 80rpx;
          line-height: 80rpx;
        }
        .button {
          position: absolute;
          background: $main_color;
          color: white;
          padding: 15rpx 30rpx;
          right: 0;
          bottom: 0;
          font-weight: 500;
          border-radius: 30rpx;
        }
      }
    }
  }
}
</style>
